package com.jiuyin.dianjing.ui.fragment.homepage;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.HomepageMsgEvent;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.PostModel;
import com.jiuyin.dianjing.model.ThumbModel;
import com.jiuyin.dianjing.ui.activity.community.PostDetailActivity;
import com.jiuyin.dianjing.ui.fragment.base.BaseRefreshLazyFragment;
import com.jiuyin.dianjing.ui.fragment.community.BottomSheetFragment;
import com.jiuyin.dianjing.ui.fragment.community.PostFragment;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.lzy.okgo.cache.CacheMode;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGANinePhotoLayout;

import static androidx.recyclerview.widget.DividerItemDecoration.VERTICAL;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ATTENTION_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_FANS_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_NICK_NAME;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SIGNATURE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TARGETID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOPIC_LIST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOPIC_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_USERID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.OSS_IMG_SCREEN_TOPIC;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_FIRST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.PAGE_NUM;
import static com.jiuyin.dianjing.api.constant.ApiConstant.VALUE_TYPE1;
import static com.jiuyin.dianjing.api.enums.ApiEnum.APP_GET_USER_DETAIL_API;
import static com.jiuyin.dianjing.model.PostModel.OWN_POSTS;


/**
 * 主页（动态）
 */
public class HomepageSecond extends BaseRefreshLazyFragment<PostModel> {
    @BindView(R.id.tv_title)
    TextView mTvTitle;

    private String mUserId = "";
    /***
     *删除帖子的索引
     */
    private int mPosition = -1;

    public HomepageSecond() {
        super(PAGE_NUM);
    }

    public static HomepageSecond newInstance(String userId) {
        HomepageSecond homepageSecond = new HomepageSecond();
        Bundle args = new Bundle();
        args.putString(KEY_USERID, userId);
        homepageSecond.setArguments(args);
        return homepageSecond;
    }

    @Override
    public void fetchData() {
        if (getArguments() != null) {
            mUserId = getArguments().getString(KEY_USERID);
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_USERID, mUserId);
        params.put(KEY_TYPE, VALUE_TYPE1);
        JSONObject jsonObject = new JSONObject(params);
        ServerApi.post(APP_GET_USER_DETAIL_API.getUrl(), jsonObject, CacheMode.NO_CACHE, null, d -> addDisposable(d),
                new ApiResultCallback() {
                    @Override
                    public void onSuccess(JsonObject jsonObject) {
                        if (null != jsonObject) {
                            String attention_num = jsonObject.get(KEY_ATTENTION_NUM).getAsString();
                            String fans_num = jsonObject.get(KEY_FANS_NUM).getAsString();
                            String topic_num = jsonObject.get(KEY_TOPIC_NUM).getAsString();
                            String sign = "";
                            if (jsonObject.has(KEY_SIGNATURE)) {
                                sign = jsonObject.get(KEY_SIGNATURE).getAsString();
                            }
                            String nickname = jsonObject.get(KEY_NICK_NAME).getAsString();
                            String id = jsonObject.get(KEY_ID).getAsString();
                            HomepageMsgEvent homepageMsgEvent = new HomepageMsgEvent();
                            homepageMsgEvent.attention_num = attention_num;
                            homepageMsgEvent.fans_num = fans_num;
                            homepageMsgEvent.topic_num = topic_num;
                            homepageMsgEvent.id = id;
                            homepageMsgEvent.sign = sign;
                            homepageMsgEvent.nickname = nickname;
                            EventBus.getDefault().post(homepageMsgEvent);
                            LogUtil.log("HomepageSecond getUserDetail onSuccess = " + jsonObject.toString());
                            if (jsonObject.has(KEY_TOPIC_LIST)) {
                                List<PostModel> postList = new Gson().fromJson(jsonObject.getAsJsonArray(KEY_TOPIC_LIST),
                                        new TypeToken<List<PostModel>>() {
                                        }.getType());
                                dealWithSuccessInfo(postList);
                            } else {
                                dealOtherInfo();
                            }
                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        LogUtil.log(msg);
                        dealOtherInfo();
                    }

                    @Override
                    public void onError(String msg) {
                        LogUtil.log(msg);
                        dealOtherInfo();
                    }
                });
        mAdapter.setOnItemClickListener((parent, view, position, id) -> {
            PostModel model = mAdapter.getItem(position);
            Bundle bundle = new Bundle();
            bundle.putSerializable(KEY_POST, model);
            goTargetActivity(PostDetailActivity.class, bundle);
        });
        DividerItemDecoration decoration = new DividerItemDecoration(getContext(), VERTICAL);
        decoration.setDrawable(getContext().getDrawable(R.drawable.decoration));
        mRcvPage.addItemDecoration(decoration);
        mRcvPage.setItemAnimator(new DefaultItemAnimator());
        mRcvPage.setAdapter(mAdapter);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_homepage_second;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseRecyclerAdapter<PostModel>(R.layout.item_post) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, PostModel model, int position) {
                if (null != model) {
                    TextView tvComment = holder.itemView.findViewById(R.id.tv_comment);
                    TextView tvClicked = holder.itemView.findViewById(R.id.tv_clicked);
                    CheckedTextView tvThumb = holder.itemView.findViewById(R.id.tv_thumb);
                    holder.text(R.id.tv_name, model.getNickname());
                    holder.text(R.id.tv_time, model.getCreate_time());
                    holder.text(R.id.tv_title, model.getTitle());
                    holder.text(R.id.tv_content, model.getContent());
                    holder.text(R.id.tv_tag_desire, model.getGenre_tag());
                    holder.text(R.id.tv_tag_game, model.getGame_tag());
                    tvComment.setText(model.getComment_num());
                    tvClicked.setText(model.getClick_num());
                    tvThumb.setText(model.getThumb_num());
                    ImageView ivHead = holder.itemView.findViewById(R.id.iv_head);
                    StringBuilder url = new StringBuilder(model.getHeader());
                    url.append(OSS_IMG_SCREEN_TOPIC);
                    Glide.with(getActivity()).load(url.toString()).into(ivHead);
                    BGANinePhotoLayout ninePhotoLayout = holder.itemView.findViewById(R.id.layout_nine_grid);
                    ArrayList<String> photos = (ArrayList<String>) model.getPhoto();
                    if (photos != null) {
                        ArrayList<String> newPhotos = new ArrayList<>(photos.size());
                        for (String str : photos) {
                            StringBuilder sb = new StringBuilder(str);
                            sb.append(OSS_IMG_SCREEN_TOPIC);
                            newPhotos.add(sb.toString());
                        }
                        ninePhotoLayout.setDelegate(new BGANinePhotoLayout.Delegate() {
                            @Override
                            public void onClickNinePhotoItem(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                photoPreviewWrapper();
                            }

                            /**
                             * 图片预览
                             */
                            private void photoPreviewWrapper() {
                                BGAPhotoPreviewActivity.IntentBuilder photoPreviewIntentBuilder =
                                        new BGAPhotoPreviewActivity.IntentBuilder(getActivity());
                                if (ninePhotoLayout.getItemCount() == 1) {
                                    // 预览单张图片
                                    photoPreviewIntentBuilder.previewPhoto(photos.get(ninePhotoLayout.getCurrentClickItemPosition()));
                                } else if (ninePhotoLayout.getItemCount() > 1) {
                                    // 预览多张图片
                                    photoPreviewIntentBuilder.previewPhotos(photos)
                                            .currentPosition(ninePhotoLayout.getCurrentClickItemPosition()); // 当前预览图片的索引
                                }
                                startActivity(photoPreviewIntentBuilder.build());
                            }

                            @Override
                            public void onClickExpand(BGANinePhotoLayout ninePhotoLayout, View view, int position, String model, List<String> models) {
                                ninePhotoLayout.setIsExpand(true);
                                ninePhotoLayout.flushItems();
                            }
                        });
                        ninePhotoLayout.setData(newPhotos);
                    }

                    holder.itemView.findViewById(R.id.iv_more).setOnClickListener(v -> {
                        mPosition = position;
                        BottomSheetFragment.newInstance(model.getTopic_id(), model.getIsOneSelf().equals(OWN_POSTS), HomepageSecond.class.getSimpleName()).show(getChildFragmentManager(), "dialog");
                    });
                    tvThumb.setOnClickListener(v -> {
                        ApiResultCallback apiResultCallback = new ApiResultCallback() {
                            @Override
                            public void onSuccess(JsonObject data) {
                                ThumbModel thumbModel = new Gson().fromJson(data, ThumbModel.class);
                                tvThumb.setChecked(thumbModel.isThumb == 1);
                                tvThumb.setText(thumbModel.thumb_num);
                                tvThumb.setEnabled(true);
                            }

                            @Override
                            public void onFail(String msg) {
                                ToastUtil.showShort(msg);
                                tvThumb.setEnabled(true);
                            }

                            @Override
                            public void onError(String msg) {
                                tvThumb.setEnabled(true);
                                LogUtil.log(msg);
                            }
                        };
                        HashMap<String, Object> params = new HashMap<>();
                        params.put(KEY_TOKEN, HelperApplication.getToken());
                        params.put(KEY_TARGETID, model.getTopic_id());
                        params.put(KEY_TYPE, tvThumb.isChecked() ? 0 : 1);
                        JSONObject json = new JSONObject(params);
                        tvThumb.setEnabled(false);
                        ServerApi.post(ApiEnum.APP_TOPIC_THUMB.getUrl(), json, null, progress, d -> addDisposable(d), apiResultCallback);
                    });
                }
            }
        };
    }

    @Override
    protected void initView() {
    }

    public void refresh() {
        if (View.GONE != mTvTitle.getVisibility()) {
            mTvTitle.setVisibility(View.GONE);
        }
        mAdapter.clear();
        mPageNum = PAGE_FIRST;
        fetchData();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RefreshEvent event) {
        if (event.clazzName.equals(getClass().getSimpleName())) {
            refresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String mTargetId) {
        if (mTargetId.equals(getClass().getSimpleName())) {
            if (mPosition != -1) {
                mAdapter.remove(mAdapter.get(mPosition));
            }
            EventBus.getDefault().post(new RefreshEvent(PostFragment.class.getSimpleName()));
        }
    }
}